package com.quanyan.user.web;

import com.quanyan.api.APIResponse;
import com.quanyan.common.mail.EmailUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.user.cache.MyRedisTemplate;
import com.quanyan.user.constants.UserConstants;
import com.quanyan.user.model.vo.request.ReqBatchQueryUserInterest;
import com.quanyan.user.model.vo.request.ReqUserInfo;
import com.quanyan.user.model.vo.request.ReqUserThirdAccount;
import com.quanyan.user.model.vo.request.ReqUserVerify;
import com.quanyan.user.model.vo.response.RespBatchUserInterest;
import com.quanyan.user.model.vo.response.RespUserThirdAccount;
import com.quanyan.user.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by zhang on 16/7/18.
 */
@RestController
@RequestMapping(value = "/api/user/c", method = RequestMethod.POST)
public class UserToCController {
    private static final Logger logger = LoggerFactory.getLogger(UserToCController.class);
    @Autowired
    private UserToCService userToCService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private MyRedisTemplate myRedisTemplate;

    @Autowired
    private UserQueryService userQueryService;

    @Autowired
    private UserTaskService userTaskService;

    @Autowired
    private UserInformationService userInformationService;

    @Autowired
    private TopicService topicService;

    @Autowired
    private UserDynamicService userDynamicService;

    private final static String userCenterAdmin = "zehai.zhang@quncaotech.com";


    /**
     * 批量查询用户的兴趣列表
     * @param
     * @return
     */
    @RequestMapping(value = "batchQueryUserInterestList")
    public APIResponse<List<RespBatchUserInterest>> batchQueryUserInterestList(@RequestBody ReqBatchQueryUserInterest reqBatchQueryUserInterest){

        List<RespBatchUserInterest> respBatchUserInterestList = this.userToCService.batchQueryUserInterestList(reqBatchQueryUserInterest.getUids());

        return APIResponse.returnSuccess(respBatchUserInterestList);
    }

    /**
     * 初始化新注册用户信息
     * @param map
     * @return
     */
    @RequestMapping(value = "initUserInfo")
    public APIResponse initUserInfo(@RequestBody Map map){
        if (map.containsKey("currentUid")) {
            this.userToCService.initUserInfo(map);
        }else{
            return APIResponse.returnFail("请传入用户ID");
        }
        return APIResponse.returnSuccess();
    }


    /**
     * 初始化新注册用户信息
     * @param map
     * @return
     */
    @RequestMapping(value = "registerClubUser")
    public APIResponse registerClubUser(@RequestBody Map map){
        Object obj = map.get("mobile");
        if( obj == null)
            return APIResponse.returnFail("请传入手机号！");
        return  userInfoService.registerClubUser(obj.toString());
    }

    /**
     * 更新运动达人信息
     * @param map
     * @return
     */
    @RequestMapping(value = "updateTalent")
    public APIResponse updateTalent(@RequestBody Map map){
        Integer uid;
        Integer type;
        if (map.containsKey("currentUid")) {
            uid = (Integer) map.get("currentUid");
        } else {
            return APIResponse.returnFail("请传入必要参数");
        }
        if (map.containsKey("type")) {
            type = (Integer) map.get("type");
        } else {
            return APIResponse.returnFail("请传入必要参数");
        }
        Integer n = userToCService.updateTalent(uid, type);
        if (n>0) {
            return APIResponse.returnSuccess();
        } else {
            return APIResponse.returnFail("达人信息更新失败");
        }
    }


    /**
     * 清理缓存
     * @return
     */
    @RequestMapping(value = "clearCache")
    public APIResponse clearCache(@RequestBody Map map){
         Integer type;
         if(map.get("type") == null)
            type = 1;
         else
             type = Integer.parseInt(map.get("type").toString());
        StringBuilder emailInfo = new StringBuilder();
        if(type.intValue() == 2){//删除全部用户信息
            logger.info("开始删除全部用户信息缓存");
             myRedisTemplate.delteKey(UserConstants.UID_MAP);
             myRedisTemplate.delteKey(UserConstants.UID_MAP_EXT);
             myRedisTemplate.delteKey(UserConstants.UID_MAP_LEVEL);
            logger.info("结束删除全部用户信息缓存");
            emailInfo.append("清除全部用户缓存信息,执行时间为:").append(DateUtils.DAY_DATE_FORMAT_HH_MM_SS.format(new Date()));

        }

         if(type.intValue() == 1){//删除单个用户信息
             logger.info("开始删除个人用户信息缓存！");
            if(map.get("uid") == null)
                return APIResponse.returnFail("uid不能为空！");
            Integer uid = Integer.parseInt(map.get("uid").toString());
             String key = UserConstants.getUserRedisKey(uid);
             String detailKey = UserConstants.getUserDetailRedisKey(uid);
             myRedisTemplate.delteKey(key);
             myRedisTemplate.delteKey(detailKey);
             myRedisTemplate.hdel(UserConstants.UID_MAP, uid.toString().getBytes());
             myRedisTemplate.hdel(UserConstants.UID_MAP_EXT, uid.toString().getBytes());
             myRedisTemplate.hdel(UserConstants.UID_MAP_LEVEL, uid.toString().getBytes());
             logger.info("结束删除uid为{}的个人用户信息缓存！",uid);
             emailInfo.append("清除uid为").append(uid).append("的用户缓存信息,执行时间为:").append(DateUtils.DAY_DATE_FORMAT_HH_MM_SS.format(new Date()));
         }


        if(type.intValue() == 3){//删除单个用户缓存任务
            logger.info("开始删除缓存任务---------------");
            if(map.get("uid") == null)
                return APIResponse.returnFail("uid不能为空！");
            Integer uid = Integer.parseInt(map.get("uid").toString());
            myRedisTemplate.hdel(UserConstants.UC_SYS_TASK, uid.toString().getBytes());
            logger.info("结束删除缓存任务---------------");
            emailInfo.append("清除uid为").append(uid).append("的用户的任务缓存信息,执行时间为:").append(DateUtils.DAY_DATE_FORMAT_HH_MM_SS.format(new Date()));
        }

        if (type.intValue() == 4) {
            logger.info("开始删除单个用户拓展信息缓存");
            if (map.get("uid") == null) {
                return APIResponse.returnFail("uid不能为空");
            }
            Integer uid = Integer.parseInt(map.get("uid").toString());
            String extKey = UserConstants.getUserExtRedisKey(uid);
            myRedisTemplate.delteKey(extKey);
            logger.info("删除缓存用户拓展信息成功：uid为【{}】",uid);
        }
        EmailUtils.getInstance().sendTextEmails(userCenterAdmin,"用户缓存清理通知",emailInfo.toString());

        return APIResponse.returnSuccess();
    }

    /**
     * 初始化用户名为空或者为null的用户
     * @return
     */
    @RequestMapping(value = "initUserNickName")
    public APIResponse initUserNickName(){
        List<Integer> uidList = userToCService.initUserNickName();
        EmailUtils.getInstance().sendTextEmails(userCenterAdmin,"用户名初始化通知","用户名初始化完成，完成时间为："+DateUtils.DAY_DATE_FORMAT_HH_MM_SS.format(new Date()));
        return APIResponse.returnSuccess(uidList);
    }

    /**
     * 更新用户出生年
     * @return
     */
    @RequestMapping(value = "updateUserYear")
    public APIResponse updateUserYear(){
        List<Integer> uidList = userToCService.updateUserYear();
        EmailUtils.getInstance().sendTextEmails(userCenterAdmin,"用户出生年初始化通知","用户出生年初始化完成，完成时间为："+DateUtils.DAY_DATE_FORMAT_HH_MM_SS.format(new Date()));
        return APIResponse.returnSuccess(uidList);
    }

    @RequestMapping(value = "noticeFriendRemark")
    public APIResponse noticeFriendRemark(@RequestBody Map map){
        try {
            Integer uid = Integer.parseInt(map.get("uid").toString());
            Integer followId = Integer.parseInt(map.get("followId").toString());
            userQueryService.setFriendRemark(uid,followId);
            return APIResponse.returnSuccess();
        } catch (Exception e) {
            logger.error("{}",e);
            return APIResponse.returnFail("");
        }
    }


    @RequestMapping(value = "taskUpdate")
    public APIResponse updateTask (@RequestBody Map map){
        try {
            Integer taskId = Integer.parseInt(map.get("taskId").toString());
            Integer type = Integer.parseInt(map.get("type").toString());
            userTaskService.setUpTask(taskId, type);
            return APIResponse.returnSuccess();
        } catch (Exception e) {
            logger.error("{}",e);
            return APIResponse.returnFail("");
        }
    }


    @RequestMapping(value = "setUpPush")
    public APIResponse setUpPush (@RequestBody Map map){
        try {
            Integer type = Integer.parseInt(map.get("type").toString());
            if (type == 0) //开启
                myRedisTemplate.set(SendMsgService.push_flag_key,SendMsgService.push_flag_value_ON );
            else if (type == 1) //关闭
                myRedisTemplate.set(SendMsgService.push_flag_key, SendMsgService.push_flag_value_OFF);
            return APIResponse.returnSuccess();
        } catch (Exception e) {
            logger.error("{}",e);
            return APIResponse.returnFail("");
        }
    }

    @RequestMapping(value = "clearImgCache")
    public APIResponse clearImgCache (@RequestBody Map map){
        try {
            Integer id = Integer.parseInt(map.get("id").toString());
            String keyImg = UserConstants.getDynamicImgKey(id);
            myRedisTemplate.delteKey(keyImg);
            return APIResponse.returnSuccess();
        } catch (Exception e) {
            logger.error("{}",e);
            return APIResponse.returnFail("");
        }
    }

    /**
     * 管理端用户实名认证
     * @param reqUserVerify
     * @return
     */
    @RequestMapping(value = "verify", method = RequestMethod.POST)
    public APIResponse verify(@RequestBody ReqUserVerify reqUserVerify){
        boolean flag = userInformationService.verify(reqUserVerify,reqUserVerify.getUid());
        if (flag) {
            return APIResponse.returnSuccess();
        } else {
            return APIResponse.returnFail("用户实名认证失败");
        }
    }

    /**
     * 管理端更新用户信息
     * @param reqUserInfo
     * @return
     */
    @RequestMapping(value = "updateUserInfo", method = RequestMethod.POST)
    public APIResponse updateUserInfo(@RequestBody ReqUserInfo reqUserInfo){
        int n = userInformationService.updateUserInfo(reqUserInfo, reqUserInfo.getUid());
        if(n>0){
            return APIResponse.returnSuccess();
        }else{
            return APIResponse.returnFail("更新失败，请重新提交");
        }
    }

    /**
     * 更新用户注册时间
     * @return
     */
    @RequestMapping(value = "updateUserRegTime")
    public APIResponse updateUserRegTime(){
        List<Integer> uidList = userToCService.updateUserRegTime();
        return APIResponse.returnSuccess(uidList);
    }



    @RequestMapping(value = "/topicList", method = RequestMethod.POST)
    public APIResponse topicList(@RequestBody List<Integer> lstTopicId){
        return topicService.batchTopic(lstTopicId);
    }

    /**
     * 更新动态只读图片状态
     * @return
     */
    @RequestMapping(value = "updateDynamicOnlyVisible")
    public APIResponse updateDynamicOnlyVisible(){
        return userDynamicService.updateDynamicOnlyVisible();
    }

    /**
     * 获取用户第三方账号列表
     * @param reqUserThirdAccount
     * @return
     */
    @RequestMapping(value = "getUserThirdAccountList")
    public APIResponse<List<RespUserThirdAccount>> getUserThirdAccountList(@RequestBody ReqUserThirdAccount reqUserThirdAccount){
        return userToCService.getUserThirdAccountList(reqUserThirdAccount);
    }

    /**
     * 初始化用户微信绑定
     * @return
     */
    @RequestMapping(value = "initUserWechat")
    public APIResponse<List<Integer>> initUserWechat(){
        return APIResponse.returnSuccess(userToCService.initUserWechat());
    }
}
